package cn.csc.module.distribute.mq.consumer;

import cn.csc.framework.common.util.collection.CollectionUtils;
import cn.csc.module.distribute.api.distributor.dto.DistributorReqDTO;
import cn.csc.module.distribute.api.order.dto.DistributeOrderDTO;
import cn.csc.module.distribute.convert.order.DistributeOrderConvert;
import cn.csc.module.distribute.dal.dataobject.downline.DistributeDownlineDO;
import cn.csc.module.distribute.dal.dataobject.order.DistributeOrderDO;
import cn.csc.module.distribute.dal.mysql.audit.DistributorAuditMapper;
import cn.csc.module.distribute.dal.mysql.distributor.DistributorMapper;
import cn.csc.module.distribute.dal.mysql.downline.DistributeDownlineMapper;
import cn.csc.module.distribute.dal.mysql.order.DistributeOrderMapper;
import cn.csc.module.distribute.service.distributor.DistributorService;
import cn.csc.module.distribute.service.order.DistributeOrderService;
import cn.csc.module.order.api.item.OrderItemApi;
import cn.csc.module.order.api.item.dto.OrderItemRespDTO;
import cn.csc.module.order.message.OrderReceiptMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

import static cn.csc.framework.common.util.json.JsonUtils.toJsonString;

/**
 * 消费买家确认收货消息
 * topic: order_receipt
 * @author liuchuang
 * @version 1.0
 * @date 2024/7/30 9:42
 * @modify
 */
@Slf4j
@Component
public class OrderReceiptConsumer {

    @Resource
    private DistributeOrderMapper distributeOrderMapper;
    @Resource
    private DistributorService distributorService;
    @Resource
    private DistributeDownlineMapper distributeDownlineMapper;
    @Resource
    private DistributorMapper distributorMapper;
    /**
     * 买家确认收货消息, 判断是否为分销订单
     * 消费 {@link OrderReceiptMessage} 消息
     * message： the input argument
     */
    @Bean
    public Consumer<OrderReceiptMessage> orderReceipt(){
        return message -> {
            log.info("OrderReceiptConsumer订单确认收货开始: {}", toJsonString(message));
            try {
                // 订单确认收货，计算可提现佣金和累计佣金,
                List<DistributeOrderDO> list = distributeOrderMapper.selectByOrderItemId(message.getOrderItemIds());
                log.info("OrderReceiptConsumer-DistributeOrderDOList: {}",list);
                if (!CollectionUtils.isAnyEmpty(list)){
                    //修改订单的状态
                    distributeOrderMapper.updateByOrderItemId(message.getOrderItemIds());
                    //订单金额
                    BigDecimal orderAmount=list.stream()
                            .map(dto ->dto.getAmount())
                            .reduce(BigDecimal.ZERO, BigDecimal::add)  // 累加所有项
                            .setScale(2, RoundingMode.HALF_UP);  // 最终结果保留两位小数
                    log.info("OrderReceiptConsumer-orderAmount: {}",orderAmount);
                    // 订单确认收货，计算入账佣金
                    BigDecimal amount=list.stream()
                            .map(dto ->dto.getAmount().multiply(new BigDecimal(dto.getCommissionRate()).divide(new BigDecimal(100))))
                            .reduce(BigDecimal.ZERO, BigDecimal::add)  // 累加所有项
                            .setScale(2, RoundingMode.HALF_UP);  // 最终结果保留两位小数
                    log.info("OrderReceiptConsumer-amount: {}",amount);
                    BigInteger userId = new BigInteger(String.valueOf(list.get(0).getUserId()));
                    log.info("OrderReceiptConsumer-userId: {}",userId);
                    DistributorReqDTO distributorReqDTO=new DistributorReqDTO();
                    distributorReqDTO.setUserId(userId)
                                     .setOrderNum(1)
                                     .setAmount(amount);
                    distributorService.withdrawable(distributorReqDTO);
                    //统计下线订单金额
                    distributeDownlineMapper.increFieldDownline(distributorMapper.selectByUserId(userId).getId(),list.get(0).getChildId(),1,amount,orderAmount);
                }
            } catch (Exception e) {
                log.error("订单确认收货消息消费失败:{}", message, e);
            }
        };
    }


}
